<?php

namespace addons\shopro\model;

use addons\shopro\exception\Exception;
use think\Db;
use think\Model;

/**
 * 活动-拼团
 */
class ActivityGroupon extends Model
{
    // 表名,不含前缀
    protected $name = 'shopro_activity_groupon';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected $hidden = [];

    // 追加属性
    protected $append = [
    ];


    // 获取正在进行中的团
    public static function getActivityGroupon($params)
    {
        $goods_id = $params['goods_id'] ?? 0;
        $activity_id = $params['activity_id'] ?? 0;

        $activityGroupons = self::with('leader')
                            ->where('goods_id', $goods_id)
                            ->where('activity_id', $activity_id)
                            ->where('status', 'ing')
                            ->limit(10)
                            ->select();

        return $activityGroupons;
    }


    // 团详情
    public static function getActivityGrouponDetail ($id) {
        $activityGroupon = self::with(['my', 'grouponLog', 'activity' => function ($query) {
            $query->removeOption('soft_delete')->with('activity_goods_sku_price');     // 关联团所属活动，并关联活动规格
        }])->where('id', $id)->find();

        if (!$activityGroupon) {
            new Exception('团未找到');
        }

        //开始-Ripple 2022-2-7 团长第一个显示
        $groupon_log = $activityGroupon['groupon_log'];
        $new_groupon_log = [];
        foreach ($groupon_log as $key=>$log){
            if ($log['is_leader'] == '1'){
                $log['goods_price'] =  Db::name('shopro_activity_goods_sku_price')
                    ->where(['activity_id'=>$log['activity_id'],'goods_id'=>$log['goods_id'],'sku_price_id'=>$log['goods_sku_price_id']])
                    ->value('price');
                $new_groupon_log[] = $log;
                unset($groupon_log[$key]);
            }else{
                $groupon_log[$key]['goods_price'] = Db::name('shopro_activity_goods_sku_price')
                    ->where(['activity_id'=>$log['activity_id'],'goods_id'=>$log['goods_id'],'sku_price_id'=>$log['goods_sku_price_id']])
                    ->value('price');
            }

        }
        $new_groupon_log = array_merge($new_groupon_log,$groupon_log);
        unset($activityGroupon['groupon_log']);
        $activityGroupon['groupon_log'] = $new_groupon_log;
        //结束-Ripple 2022-2-7 团长第一个显示


        //开始-Ripple 2022-2-7 团售后申请
        $user = User::info();
        $activityGroupon['my_groupon_after_sale'] = [];//标记我自己的申请
        $groupon_after_sale = Db::name('shopro_activity_groupon_after_sale')->alias('s')
                                ->join('user u','u.id=s.user_id','left')
                                ->where(['s.activity_groupon_id'=>$activityGroupon['id']])
                                ->field('s.id,s.activity_groupon_id,s.user_id,s.application_remark,s.application_time,s.processing_time,s.processing_results,s.processing_remark,
                                u.nickname,u.avatar,u.mobile')
                                ->select();
        foreach ($groupon_after_sale as $key=>$value){
            $groupon_after_sale[$key]['application_time'] = date('Y-m-d H:i:s',$value['application_time']);
            $groupon_after_sale[$key]['processing_time'] = empty($value['processing_time']) ? '':date('Y-m-d H:i:s',$value['processing_time']);

            //获取用户参团记录
            $order_id = Db::name('shopro_activity_groupon_log')
                        ->where([
                            'user_id' => $value['user_id'],
                            'groupon_id' => $value['activity_groupon_id'],
                            'is_fictitious' => 0,
                            'is_refund' => 0
                        ])->value('order_id');
            $order_item_info = Db::name('shopro_order_item')
                ->where(['order_id'=>$order_id,'user_id'=>$value['user_id']])
                ->field('dispatch_type,dispatch_status')
                ->find();
            $groupon_after_sale[$key]['order_item_info'] = $order_item_info;

            //取最新一条
            if (!empty($user) && ($user->id == $value['user_id']) && empty($activityGroupon['my_groupon_after_sale'])){
                $activityGroupon['my_groupon_after_sale'] = $groupon_after_sale[$key];
            }
        }
        $activityGroupon['groupon_after_sale'] = $groupon_after_sale;
        //结束-Ripple 2022-2-7 团售后申请

        $detail = Goods::getGoodsDetail($activityGroupon['goods_id']);      // 正常团选规格时候要用
        $activityGroupon['goods'] = $detail;

        // 初始化拼团价为商品价，防止活动被物理删除
        $activityGroupon['goods']['groupon_price'] = $activityGroupon['goods']['price'];
        // 初始化活动状态为已结束
        $activityGroupon['activity_status'] = 'ended';

        // 处理当时的活动价格
        if ($activityGroupon['activity']) {
            $activity = $activityGroupon['activity'];
            $activityGroupon['activity_status'] = $activity['status_code'];

            $currentGoodsActivitySkuPrices = [];
            foreach ($activity['activity_goods_sku_price'] as $k => $skuPrice) {
                if ($skuPrice['status'] == 'up' && $skuPrice['goods_id'] == $activityGroupon['goods_id']) {
                    $currentGoodsActivitySkuPrices[] = $skuPrice;
                }
            }

            if ($currentGoodsActivitySkuPrices) {
                // 当时参加活动真实销量
                $activityGroupon['goods']['sales'] = array_sum(array_column($currentGoodsActivitySkuPrices, 'sales'));
                // 这个是活动最低价
                $activityGroupon['goods']['groupon_price'] = $activityGroupon['goods']['price'] = min(array_column($currentGoodsActivitySkuPrices, 'price'));
            }
        }



        $sds = Db::name('shopro_activity_groupon')->where('id',$activityGroupon['groupon_log'][0]['groupon_id'])->where('user_id',$activityGroupon['groupon_log'][0]['user_id'])->find();
        if ($sds['order_top_groupon_id']==0){
            $activityGroupon['groupon_layer'] = 1;

            //获取团长名称
            $activityGroupon['groupon_open_name'] = Db::name('shopro_group_identity')
                ->where(['user_id'=>$activityGroupon['user_id'],'activity_groupon_id'=>0,'parent_groupon_id'=>0,'level'=>1])
                ->value('name');

        }else{
            $dd = Db::name('shopro_group_identity')->where('activity_groupon_id',$sds['order_top_groupon_id'])->where('user_id',$activityGroupon['groupon_log'][0]['user_id'])->find();
            $activityGroupon['groupon_layer'] = $dd['level'];

            //获取团长名称
            $activityGroupon['groupon_open_name'] = Db::name('user')
                ->where(['id'=>$activityGroupon['user_id']])
                ->value('nickname');
        }
        if (!empty($activityGroupon['my'])){
            if ($activityGroupon['my']['user_id']==$activityGroupon['user_id']){//是当前团团长

                    if (empty($sds['order_top_groupon_id'])){
                        $infoo = Db::name('shopro_group_identity')
                            ->where('activity_id',$activityGroupon['activity_id'])
                            ->where('activity_groupon_id',$activityGroupon['my']['groupon_id'])
                            ->where('parent_groupon_id',0)
                            ->where('user_id',$activityGroupon['my']['user_id'])
                            ->field('commission_type,commission_money,commission_bili,level,status')
                            ->find();
                    }else{
                        $infoo = Db::name('shopro_group_identity')
                            ->where('activity_id',$activityGroupon['activity_id'])
                            ->where('activity_groupon_id',$activityGroupon['order_top_groupon_id'])
                            ->where('parent_groupon_id',$activityGroupon['order_superior_groupon_id'])
                            ->where('user_id',$activityGroupon['my']['user_id'])
                            ->field('commission_type,commission_money,commission_bili,level,status')
                            ->find();
                    }


                $dd =2;



            }else{//不是当前团团长
                if (empty($sds['order_top_groupon_id'])){//无顶团，当前团作为顶团
                    $infoo = Db::name('shopro_group_identity')
                        ->where('activity_id',$activityGroupon['my']['activity_id'])
                        ->where('activity_groupon_id',$activityGroupon['my']['groupon_id'])
                        ->where('parent_groupon_id',$activityGroupon['my']['groupon_id'])
                        ->where('user_id',$activityGroupon['my']['user_id'])
                        ->field('commission_type,commission_money,commission_bili,level,status')
                        ->find();

                    $dd =0;
                    if (!empty($infoo) && $infoo['status']==0){
                        $dd =1;  //团长状态审核中
                    }
                    if (!empty($infoo) && $infoo['status']==1){
                        $dd =2; //团长状态审核成功
                    }

                }else{//有顶团
                    $infoo = Db::name('shopro_group_identity')
                        ->where('activity_id',$activityGroupon['my']['activity_id'])
                        ->where('activity_groupon_id',$sds['order_top_groupon_id'])
                        ->where('parent_groupon_id',$activityGroupon['my']['groupon_id'])
                        ->where('user_id',$activityGroupon['my']['user_id'])
                        ->field('commission_type,commission_money,commission_bili,level,status')
                        ->find();
                    $dd =0;
                    if (!empty($infoo) && $infoo['status']==0){
                        $dd =1;  //团长状态审核中
                    }
                    if (!empty($infoo) && $infoo['status']==1){
                        $dd =2; //团长状态审核成功
                    }
                }
            }


            $infoo['btn_status'] = $dd;

            $activityGroupon['my']['infoo']=$infoo;



            if ($infoo){
                $activityGroupon['my']['infoo']=$infoo;
            }
        }

        //获取团长头像、团长介绍、团长介绍图片、团长服务承诺、团长标签、团员人数、跟团人次
        $opend_groupon_user_info = Db::name('user')->field('id,avatar,head_introduction,head_introduction_images,head_service_commitment,head_label')->where(['id'=>$activityGroupon['user_id']])->find();
        if (!empty($opend_groupon_user_info)){
            $opend_groupon_user_info['avatar'] = empty($opend_groupon_user_info['avatar'])? '':cdnurl($opend_groupon_user_info['avatar'],true);

            $opend_groupon_user_info['head_introduction_images_array'] = empty($opend_groupon_user_info['head_introduction_images'])? []: explode(',',$opend_groupon_user_info['head_introduction_images']);
            foreach ($opend_groupon_user_info['head_introduction_images_array'] as &$head_introduction_image){
                $head_introduction_image = empty($head_introduction_image)? '':cdnurl($head_introduction_image,true);
            }
            unset($head_introduction_image);

            //统计团员人数
            $opend_groupon_user_info['number_league_members'] = intval(Db::name('user')->where(['parent_user_id'=>$opend_groupon_user_info['id']])->count());

            //统计跟团人次
            $opend_groupon_user_info['group_attendance'] = intval(Db::name('shopro_activity_groupon')->where(['user_id'=>$opend_groupon_user_info['id']])->sum('current_num'));
        }

        $activityGroupon['groupon_open_avatar'] = isset($opend_groupon_user_info['avatar'])? $opend_groupon_user_info['avatar']:'';
        $activityGroupon['groupon_open_head_introduction'] = isset($opend_groupon_user_info['head_introduction'])? $opend_groupon_user_info['head_introduction']:'';
        $activityGroupon['groupon_open_head_introduction_images'] = isset($opend_groupon_user_info['head_introduction_images'])? $opend_groupon_user_info['head_introduction_images']:'';
        $activityGroupon['groupon_open_head_introduction_images_array'] = isset($opend_groupon_user_info['head_introduction_images_array'])? $opend_groupon_user_info['head_introduction_images_array']:'';
        $activityGroupon['groupon_open_head_service_commitment'] = isset($opend_groupon_user_info['head_service_commitment'])? $opend_groupon_user_info['head_service_commitment']:'';
        $activityGroupon['groupon_open_head_label'] = isset($opend_groupon_user_info['head_label'])? $opend_groupon_user_info['head_label']:'';
        $activityGroupon['groupon_open_number_league_members'] = isset($opend_groupon_user_info['number_league_members'])? $opend_groupon_user_info['number_league_members']:0;
        $activityGroupon['groupon_open_group_attendance'] = isset($opend_groupon_user_info['group_attendance'])? $opend_groupon_user_info['group_attendance']:0;

        //获取成团人数最低、最高   拼团有效期最低、最高
        $mix_user_num = empty(config('site.config_mix_user_num')) ? 2:config('site.config_mix_user_num');
        $max_user_num = empty(config('site.config_max_user_num')) ? 999:config('site.config_max_user_num');
        $mix_groupn_hour = empty(config('site.config_mix_groupn_hour')) ? 1:config('site.config_mix_groupn_hour');
        $max_groupn_hour = empty(config('site.config_max_groupn_hour')) ? 999:config('site.config_max_groupn_hour');
        $activityGroupon['mix_user_num'] = $mix_user_num;
        $activityGroupon['max_user_num'] = $max_user_num;
        $activityGroupon['mix_groupn_hour'] = $mix_groupn_hour;
        $activityGroupon['max_groupn_hour'] = $max_groupn_hour;

        return $activityGroupon;
    }



    /**
     * 获取我的拼团列表
     *
     * @param [type] $type
     * @return void
     */
    public static function getMyGroupon($type) {
        $user = User::info();

        $logs = \addons\shopro\model\ActivityGrouponLog::with(['groupon', 'order.firstItem', 'goods' => function ($query) {
            $query->removeOption('soft_delete');        // 商品查询包括被软删除的
        }]);

        if ($type != 'all') {
            $type = $type == 'finish' ? ['finish', 'finish-fictitious'] : [$type];
            $logs = $logs->whereExists(function ($query) use ($type) {
                $log_name = (new \addons\shopro\model\ActivityGrouponLog())->getQuery()->getTable();
                $groupon_name = (new \addons\shopro\model\ActivityGroupon())->getQuery()->getTable();
                $query->table($groupon_name)->where('id=' . $log_name . '.groupon_id')
                        ->where('status', 'in', $type);
            });
        }

        $logs = $logs->where('user_id', $user->id)
                ->order('id', 'desc')
                ->paginate(10)->toArray();

        // 将列表的显示价格，都查当时购买的价格，和当时对应的活动的 真实销量
        if ($grouponLogs = $logs['data']) {
            // 拿到所有活动 ids
            $activity_ids = array_column($grouponLogs, 'activity_id');

            // 一次获取所有活动，包括被软删除的活动，并关联规格
            $activities = \addons\shopro\model\Activity::withTrashed()
                ->with('activityGoodsSkuPrice')
                ->where('id', 'in', $activity_ids)->select();
            $activities = array_column($activities, null, 'id');

            foreach ($grouponLogs as $key => $grouponLog) {
                if (isset($grouponLog['goods']) && $grouponLog['goods'] && isset($activities[$grouponLog['activity_id']])) {
                    $activity = $activities[$grouponLog['activity_id']];

                    // 拿到当前商品对应的活动规格
                    $currentGoodsActivitySkuPrices = [];
                    foreach ($activity['activityGoodsSkuPrice'] as $k => $skuPrice) {
                        if ($skuPrice['status'] == 'up' && $skuPrice['goods_id'] == $grouponLog['goods_id']) {
                            $currentGoodsActivitySkuPrices[] = $skuPrice;
                        }
                    }

                    // 当时参加活动真实销量
                    if ($currentGoodsActivitySkuPrices) {
                        $grouponLogs[$key]['goods']['sales'] = array_sum(array_column($currentGoodsActivitySkuPrices, 'sales'));
                    }
                    // 这个是购买时候的活动单价
                    if (isset($grouponLog['order']['first_item'])) {
                        $grouponLogs[$key]['goods']['price'] = $grouponLog['order']['first_item']['goods_price'];
                    }
                }
                $ddd = 0;
                $sds = Db::name('shopro_activity_groupon')->where('id',$grouponLog['groupon_id'])->find();
                if ($sds['order_top_groupon_id']==0){
                    $groupon_layer = 1;
                    $ddd= 2;
                }else{
                    $dd = Db::name('shopro_group_identity')->where('activity_groupon_id',$sds['order_top_groupon_id'])->where('user_id',$sds['user_id'])->find();
                    $groupon_layer = intval($dd['level']);
                    $ddd= 3;
                }
                $count = 0;
                if ($groupon_layer<3){
                    $count = Db::name('shopro_group_identity')
                        ->alias('i')
                        ->join('user u','u.id = i.user_id')
                        ->where('i.activity_groupon_id',$grouponLog['groupon_id'])
                        ->where('i.parent_user_id',$user->id)
                        ->where('i.level',$ddd)
                        ->where('i.status',0)
                        ->field('i.*,u.nickname,u.avatar,u.mobile')
                        ->count();

                }
                $grouponLogs[$key]['groupon_layer'] = $groupon_layer;
                $grouponLogs[$key]['apply_list_count'] = $count;
            }

            $logs['data'] = $grouponLogs;
        }

        return $logs;
    }


    public function activity() 
    {
        return $this->belongsTo(\addons\shopro\model\Activity::class, 'activity_id', 'id');
    }


    public function grouponLog()
    {
        return $this->hasMany(\addons\shopro\model\ActivityGrouponLog::class, 'groupon_id', 'id');
    }

    public function leader() {
        return $this->hasOne(\addons\shopro\model\ActivityGrouponLog::class, 'groupon_id', 'id')->where('is_leader', 1);
    }

    public function my() {
        $user = User::info();
        return $this->hasOne(\addons\shopro\model\ActivityGrouponLog::class, 'groupon_id', 'id')->where('user_id', ($user ? $user->id : 0));
    }

    public function goods()
    {
        return $this->belongsTo(\addons\shopro\model\Goods::class, 'goods_id', 'id');
    }
}
